layui.define(['jquery', 'table', 'form', 'layer', 'laydate'], function(exports) {
    var $ = layui.jquery, 
        table = layui.table, 
        form = layui.form, 
        layer = layui.layer,
        laydate = layui.laydate;

    var tableIns;

    function init() {
        renderTable();
        bindEvents();
    }

    function renderTable() {
        // 渲染表格
        tableIns = table.render({
            elem: '#bookTable',
            url: '/book/list',
            method: 'get',
            toolbar: '#bookToolbar',
            defaultToolbar: ['filter', 'exports', 'print'],
            parseData: function(res) {
                return {
                    "code": res.code === 200 ? 0 : res.code,
                    "msg": res.message,
                    "count": res.data ? res.data.total : 0,
                    "data": res.data ? res.data.records : []
                };
            },
            cols: [[
                {type: 'checkbox', fixed: 'left'},
                {field: 'id', title: 'ID', width: 80, sort: true},
                {field: 'isbn', title: 'ISBN', width: 120},
                {field: 'title', title: '书名', width: 200},
                {field: 'subtitle', title: '副标题', width: 150},
                {field: 'authorName', title: '作者', width: 100},
                {field: 'publisherName', title: '出版社', width: 120},
                {field: 'categoryName', title: '分类', width: 100},
                {field: 'price', title: '价格', width: 80},
                {field: 'stock', title: '库存', width: 80},
                {field: 'borrowedCount', title: '借阅次数', width: 100},
                {field: 'publishDate', title: '出版日期', width: 120, templet: function(d) {
                    return d.publishDate ? new Date(d.publishDate).toLocaleDateString() : '';
                }},
                {title: '操作', width: 200, align: 'center', fixed: 'right', toolbar: '#bookBar'}
            ]],
            page: true,
            limit: 10,
            limits: [10, 20, 50, 100]
        });
    }

    function bindEvents() {
        // 搜索按钮
        form.on('submit(bookSearch)', function(data) {
            tableIns.reload({
                where: data.field,
                page: {curr: 1}
            });
            return false;
        });

        // 重置按钮
        $('#bookReset').on('click', function() {
            $('#bookSearchForm')[0].reset();
            tableIns.reload({
                where: {},
                page: {curr: 1}
            });
        });

        // 新增按钮
        $('#bookAdd').on('click', function() {
            showBookDialog();
        });

        // 批量删除按钮
        $('#bookDeleteBatch').on('click', function() {
            var checkStatus = table.checkStatus('bookTable');
            var data = checkStatus.data;
            if (data.length === 0) {
                layer.msg('请选择要删除的数据', {icon: 2});
                return;
            }
            
            var ids = data.map(function(item) {
                return item.id;
            });
            
            layer.confirm('确定要删除选中的图书吗？', function(index) {
                $.post('/book/deleteBatch', {ids: ids}, function(res) {
                    if (res.code === 200) {
                        layer.msg('删除成功', {icon: 1});
                        tableIns.reload();
                    } else {
                        layer.msg(res.message || '删除失败', {icon: 2});
                    }
                }).fail(function() {
                    layer.msg('网络错误，请稍后重试', {icon: 2});
                });
                layer.close(index);
            });
        });

        // 表格工具条事件
        table.on('tool(bookTable)', function(obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                showBookDialog(data);
            } else if (obj.event === 'del') {
                layer.confirm('确定删除此图书？', function(index) {
                    $.post('/book/delete', {id: data.id}, function(res) {
                        if (res.code === 200) {
                            layer.msg('删除成功', {icon: 1});
                            obj.del();
                        } else {
                            layer.msg(res.message || '删除失败', {icon: 2});
                        }
                    }).fail(function() {
                        layer.msg('网络错误，请稍后重试', {icon: 2});
                    });
                    layer.close(index);
                });
            }
        });
    }

    function showBookDialog(data) {
        var title = data ? '编辑图书' : '新增图书';
        var bookHtml = `
            <form class="layui-form" id="bookForm" style="padding: 20px;">
                <input type="hidden" name="id" value="${data ? data.id : ''}">
                <div class="layui-form-item">
                    <label class="layui-form-label">ISBN</label>
                    <div class="layui-input-block">
                        <input type="text" name="isbn" required lay-verify="required" placeholder="请输入ISBN" value="${data ? data.isbn : ''}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">书名</label>
                    <div class="layui-input-block">
                        <input type="text" name="title" required lay-verify="required" placeholder="请输入书名" value="${data ? data.title : ''}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">副标题</label>
                    <div class="layui-input-block">
                        <input type="text" name="subtitle" placeholder="请输入副标题" value="${data ? data.subtitle : ''}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">作者</label>
                    <div class="layui-input-block">
                        <select name="authorId" lay-verify="required" lay-search>
                            <option value="">请选择作者</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">出版社</label>
                    <div class="layui-input-block">
                        <select name="publisherId" lay-verify="required" lay-search>
                            <option value="">请选择出版社</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">分类</label>
                    <div class="layui-input-block">
                        <select name="categoryId" lay-verify="required" lay-search>
                            <option value="">请选择分类</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">价格</label>
                    <div class="layui-input-block">
                        <input type="number" name="price" step="0.01" placeholder="请输入价格" value="${data ? data.price : ''}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">库存</label>
                    <div class="layui-input-block">
                        <input type="number" name="stock" placeholder="请输入库存" value="${data ? data.stock : ''}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">页数</label>
                    <div class="layui-input-block">
                        <input type="number" name="pageCount" placeholder="请输入页数" value="${data ? data.pageCount : ''}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">语言</label>
                    <div class="layui-input-block">
                        <input type="text" name="language" placeholder="请输入语言" value="${data ? data.language : ''}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">出版日期</label>
                    <div class="layui-input-block">
                        <input type="text" name="publishDate" id="publishDate" placeholder="请选择出版日期" value="${data ? data.publishDate : ''}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">简介</label>
                    <div class="layui-input-block">
                        <textarea name="description" placeholder="请输入图书简介" class="layui-textarea">${data ? data.description : ''}</textarea>
                    </div>
                </div>
            </form>
        `;

        var dialog = layer.open({
            type: 1,
            title: title,
            area: ['600px', '600px'],
            content: bookHtml,
            btn: ['确定', '取消'],
            success: function(layero, index) {
                // 初始化日期选择器
                laydate.render({
                    elem: '#publishDate'
                });
                
                // 加载下拉选项数据
                loadSelectOptions();
                
                // 如果是编辑，设置选中值
                if (data) {
                    setTimeout(function() {
                        form.val('bookForm', data);
                    }, 100);
                }
                
                form.render();
            },
            yes: function(index, layero) {
                var formData = form.val('bookForm');
                
                // 发送请求
                var url = formData.id ? '/book/update' : '/book/add';
                $.post(url, formData, function(res) {
                    if (res.code === 200) {
                        layer.msg(formData.id ? '修改成功' : '添加成功', {icon: 1});
                        layer.close(index);
                        tableIns.reload();
                    } else {
                        layer.msg(res.message || '操作失败', {icon: 2});
                    }
                }).fail(function() {
                    layer.msg('网络错误，请稍后重试', {icon: 2});
                });
            }
        });
    }

    function loadSelectOptions() {
        // 加载作者选项
        $.get('/author/list', function(res) {
            if (res.code === 200 && res.data && res.data.records) {
                var options = '<option value="">请选择作者</option>';
                res.data.records.forEach(function(item) {
                    options += '<option value="' + item.id + '">' + item.name + '</option>';
                });
                $('select[name="authorId"]').html(options);
                form.render('select');
            }
        });

        // 加载出版社选项
        $.get('/publisher/list', function(res) {
            if (res.code === 200 && res.data && res.data.records) {
                var options = '<option value="">请选择出版社</option>';
                res.data.records.forEach(function(item) {
                    options += '<option value="' + item.id + '">' + item.name + '</option>';
                });
                $('select[name="publisherId"]').html(options);
                form.render('select');
            }
        });

        // 加载分类选项
        $.get('/category/list', function(res) {
            if (res.code === 200 && res.data && res.data.records) {
                var options = '<option value="">请选择分类</option>';
                res.data.records.forEach(function(item) {
                    options += '<option value="' + item.id + '">' + item.name + '</option>';
                });
                $('select[name="categoryId"]').html(options);
                form.render('select');
            }
        });
    }

    exports('book', { init: init });
}); 